<template>
  <div class="version-container">
    <div class="page-header">
      <el-page-header @back="goBack" :content="phoneInfo && phoneInfo.name ? `${phoneInfo.name} (${phoneInfo.model})` : '加载中...'"></el-page-header>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="版本号">
          <el-input v-model="searchForm.version" placeholder="请输入版本号" clearable></el-input>
        </el-form-item>
        <el-form-item label="地区">
          <el-select v-model="searchForm.region" placeholder="请选择地区" clearable>
            <el-option label="国内版" value="normal"></el-option>
            <el-option label="国际版" value="international"></el-option>
            <el-option label="欧洲经济区" value="eea"></el-option>
            <el-option label="俄罗斯" value="russia"></el-option>
            <el-option label="印度" value="india"></el-option>
            <el-option label="印尼" value="indonesia"></el-option>
            <el-option label="土耳其" value="turkey"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">查询</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
          <el-button type="warning" @click="handleReset">重置</el-button>
          <el-button type="info" @click="loadData">刷新</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading" element-loading-text="加载中..." :empty-text="tableEmpty">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="version" label="版本号"></el-table-column>
      <el-table-column label="发布日期" width="120">
        <template slot-scope="scope">
          {{ formatDate(scope.row.date) }}
        </template>
      </el-table-column>
      <el-table-column prop="androidVersion" label="安卓版本" width="120"></el-table-column>
      <el-table-column label="卡刷包" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.hasCardFlash" type="success">有</el-tag>
          <el-tag v-else type="info">无</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="线刷包" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.hasLineFlash" type="success">有</el-tag>
          <el-tag v-else type="info">无</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="地区" width="120">
        <template slot-scope="scope">
          <el-tag>{{ getRegionName(scope.row.region) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="220">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="success" size="small" @click="handleDownload(scope.row)">下载链接</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="500px">
      <el-form :model="form" :rules="rules" ref="versionForm" label-width="120px">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入版本号"></el-input>
        </el-form-item>
        <el-form-item label="发布日期" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="安卓版本" prop="androidVersion">
          <el-input v-model="form.androidVersion" placeholder="请输入安卓版本"></el-input>
        </el-form-item>
        <el-form-item label="是否有卡刷包" prop="hasCardFlash">
          <el-switch v-model="form.hasCardFlash"></el-switch>
        </el-form-item>
        <el-form-item label="是否有线刷包" prop="hasLineFlash">
          <el-switch v-model="form.hasLineFlash"></el-switch>
        </el-form-item>
        <el-form-item label="地区" prop="region">
          <el-select v-model="form.region" placeholder="请选择地区" style="width: 100%;">
            <el-option label="国内版" value="normal"></el-option>
            <el-option label="国际版" value="international"></el-option>
            <el-option label="欧洲经济区" value="eea"></el-option>
            <el-option label="俄罗斯" value="russia"></el-option>
            <el-option label="印度" value="india"></el-option>
            <el-option label="印尼" value="indonesia"></el-option>
            <el-option label="土耳其" value="turkey"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 下载链接对话框 -->
    <el-dialog title="下载链接管理" :visible.sync="downloadDialog.visible" width="680px">
      <el-tabs v-model="downloadDialog.activeTab">
        <el-tab-pane label="卡刷包链接" name="card" v-if="currentVersion && currentVersion.hasCardFlash">
          <div class="download-links">
            <div v-for="(link, index) in downloadLinks.card" :key="index" class="download-link-item">
              <el-input v-model="link.name" placeholder="链接名称" class="link-name"></el-input>
              <el-input v-model="link.url" placeholder="下载地址URL" class="link-url"></el-input>
              <el-button type="danger" @click="removeDownloadLink('card', index)">删除</el-button>
            </div>
            <div class="download-link-actions">
              <el-button type="primary" @click="addDownloadLink('card')">添加卡刷包链接</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="线刷包链接" name="line" v-if="currentVersion && currentVersion.hasLineFlash">
          <div class="download-links">
            <div v-for="(link, index) in downloadLinks.line" :key="index" class="download-link-item">
              <el-input v-model="link.name" placeholder="链接名称" class="link-name"></el-input>
              <el-input v-model="link.url" placeholder="下载地址URL" class="link-url"></el-input>
              <el-button type="danger" @click="removeDownloadLink('line', index)">删除</el-button>
            </div>
            <div class="download-link-actions">
              <el-button type="primary" @click="addDownloadLink('line')">添加线刷包链接</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="downloadDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="saveDownloadLinks">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { phoneApi, versionApi, downloadApi } from '@/utils/api'
import axios from 'axios'

export default {
  name: 'Version',
  data() {
    return {
      phoneId: null,
      phoneInfo: {
        name: '',
        model: ''
      },
      searchForm: {
        version: '',
        region: ''
      },
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      loading: false,
      tableEmpty: '暂无数据',
      dialog: {
        title: '',
        visible: false,
        type: 'add' // add 或 edit
      },
      form: {
        id: null,
        version: '',
        date: '',
        androidVersion: '',
        hasCardFlash: false,
        hasLineFlash: false,
        phoneId: null,
        region: 'normal'
      },
      rules: {
        version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
        date: [{ required: true, message: '请选择发布日期', trigger: 'change' }],
        androidVersion: [{ required: true, message: '请输入安卓版本', trigger: 'blur' }],
        region: [{ required: true, message: '请选择地区', trigger: 'change' }]
      },
      downloadDialog: {
        visible: false,
        activeTab: 'card'
      },
      currentVersion: null,
      downloadLinks: {
        card: [],
        line: []
      },
      regionMap: {
        normal: '国内版',
        international: '国际版',
        eea: '欧洲经济区',
        russia: '俄罗斯',
        india: '印度',
        indonesia: '印尼',
        turkey: '土耳其'
      }
    }
  },
  created() {
    console.log('路由查询参数:', this.$route.query)
    this.phoneId = parseInt(this.$route.query.phoneId)
    console.log('解析后的phoneId:', this.phoneId)
    
    if (this.phoneId) {
      this.getPhoneInfo()
      this.loadData()
    } else {
      console.error('缺少手机ID参数')
      this.$message.error('缺少手机ID参数')
      this.goBack()
    }
  },
  methods: {
    // 重置按钮
    handleReset() {
      // 重置搜索表单
      this.searchForm = {
        version: '',
        region: ''
      }
      // 重置页码到第一页
      this.page.pageNum = 1
      // 重新加载数据
      this.loadData()
    },
    getPhoneInfo() {
      console.log('获取手机信息, phoneId:', this.phoneId)
      phoneApi.getPhoneById(this.phoneId)
        .then(res => {
          console.log('获取手机信息结果:', res)
          if (res.code === 200 || res.code === "200") {
            this.phoneInfo = res.data || {}
            console.log('更新后的phoneInfo:', this.phoneInfo)
          } else {
            this.$message.error('获取手机信息失败：' + res.msg)
          }
        })
        .catch(err => {
          console.error('获取手机信息错误:', err)
          this.$message.error('获取手机信息失败：' + (err.message || '未知错误'))
        })
    },
    // 加载列表数据
    loadData() {
      console.log('执行loadData方法，参数：', {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        phoneId: this.phoneId,
        version: this.searchForm.version,
        region: this.searchForm.region
      })
      
      // 确保phoneId存在
      if (!this.phoneId) {
        console.error('phoneId不存在，无法查询')
        this.$message.error('手机ID参数缺失，请返回列表页重新选择')
        return
      }
      
      // 只传递有值的参数
      const params = {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        phoneId: this.phoneId
      }
      
      // 只有当用户输入了版本号才添加到查询参数
      if (this.searchForm.version && this.searchForm.version.trim() !== '') {
        params.version = this.searchForm.version.trim()
      }
      
      // 只有当用户选择了地区才添加到查询参数
      if (this.searchForm.region) {
        params.region = this.searchForm.region
      }
      
      // 打印完整请求信息
      console.log('API请求参数:', params)
      
      this.loading = true
      this.tableEmpty = '加载中...'
      
      versionApi.getVersionPage(params)
        .then(res => {
          this.loading = false
          console.log('API返回数据：', res)
          if (res.code === 200 || res.code === "200") {
            console.log('表格数据:', res.data)
            if (res.data && res.data.list) {
              this.tableData = res.data.list
              this.page.total = res.data.total || 0
              this.tableEmpty = this.tableData.length === 0 ? '没有找到符合条件的数据' : '暂无数据'
              console.log('更新后的表格数据:', this.tableData)
              
              // 处理可能存在的日期格式问题
              this.tableData.forEach(item => {
                if (item.date && typeof item.date === 'string' && item.date.includes('YYYY')) {
                  // 在显示时会通过formatDate处理，此处不直接修改数据
                  console.log(`检测到日期格式问题：${item.id}, ${item.date}`)
                }
              })
            } else {
              this.tableData = []
              this.page.total = 0
              this.tableEmpty = '返回数据格式不正确'
              console.log('API返回数据格式不符合预期')
            }
          } else {
            this.tableData = []
            this.page.total = 0
            this.tableEmpty = '获取数据失败：' + res.msg
            this.$message.error('获取数据失败：' + res.msg)
          }
        })
        .catch(err => {
          this.loading = false
          this.tableData = []
          this.page.total = 0
          this.tableEmpty = '获取数据出错，请稍后重试'
          console.error('获取版本列表失败：', err)
          this.$message.error('获取数据失败：' + (err.message || '未知错误'))
        })
    },
    // 查询按钮
    handleSearch() {
      console.log('触发查询按钮')
      this.page.pageNum = 1
      this.loadData()
    },
    // 新增按钮
    handleAdd() {
      console.log('触发新增按钮, 当前phoneId:', this.phoneId)
      
      if (!this.phoneId) {
        this.$message.error('手机ID参数缺失，无法添加新版本')
        return
      }
      
      this.dialog.title = '新增固件版本'
      this.dialog.type = 'add'
      this.dialog.visible = true
      this.form = {
        id: null,
        version: '',
        date: '',
        androidVersion: '',
        hasCardFlash: false,
        hasLineFlash: false,
        phoneId: this.phoneId,
        region: 'normal'
      }
      
      console.log('初始化表单数据:', this.form)
    },
    // 编辑按钮
    handleEdit(row) {
      this.dialog.title = '编辑固件版本'
      this.dialog.type = 'edit'
      this.dialog.visible = true
      
      // 创建表单数据的深拷贝
      const formData = JSON.parse(JSON.stringify(row))
      
      // 处理日期格式
      if (formData.date && formData.date.includes('YYYY')) {
        formData.date = formData.date.replace('YYYY', new Date().getFullYear())
      }
      
      this.form = formData
    },
    // 下载链接按钮
    handleDownload(row) {
      this.currentVersion = row
      this.downloadDialog.visible = true
      this.downloadDialog.activeTab = row.hasCardFlash ? 'card' : 'line'
      
      // 加载下载链接
      downloadApi.getDownloadByVersionId(row.id).then(res => {
        const links = res.data
        this.downloadLinks = {
          card: links.card || [],
          line: links.line || []
        }
      })
    },
    // 删除按钮
    handleDelete(row) {
      this.$confirm('确认删除该固件版本及关联的下载链接吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        versionApi.deleteVersion(row.id).then((res) => {
          if (res.code === 200 || res.code === "200") {
            this.$message.success('删除成功')
            this.loadData()
            this.getPhoneInfo() // 更新手机信息（固件数量）
          } else {
            this.$message.error('删除失败：' + res.msg)
          }
        }).catch(err => {
          console.error('删除版本错误:', err)
          this.$message.error('删除失败：' + (err.message || '未知错误'))
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 提交表单
    submitForm() {
      this.$refs.versionForm.validate((valid) => {
        if (valid) {
          console.log('提交表单数据:', this.form)
          
          // 确保phoneId存在
          if (!this.form.phoneId) {
            this.form.phoneId = this.phoneId
          }
          
          if (this.dialog.type === 'add') {
            versionApi.addVersion(this.form)
              .then(res => {
                console.log('新增版本结果:', res)
                if (res.code === 200 || res.code === "200") {
                  this.$message.success('新增成功')
                  this.dialog.visible = false
                  this.loadData()
                  this.getPhoneInfo() // 更新手机信息（固件数量）
                } else {
                  this.$message.error('新增失败：' + res.msg)
                }
              })
              .catch(err => {
                console.error('新增版本错误:', err)
                this.$message.error('新增失败：' + (err.message || '未知错误'))
              })
          } else {
            versionApi.updateVersion(this.form)
              .then(res => {
                console.log('更新版本结果:', res)
                if (res.code === 200 || res.code === "200") {
                  this.$message.success('更新成功')
                  this.dialog.visible = false
                  this.loadData()
                } else {
                  this.$message.error('更新失败：' + res.msg)
                }
              })
              .catch(err => {
                console.error('更新版本错误:', err)
                this.$message.error('更新失败：' + (err.message || '未知错误'))
              })
          }
        } else {
          return false
        }
      })
    },
    // 每页条数变化
    handleSizeChange(val) {
      this.page.pageSize = val
      this.loadData()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.loadData()
    },
    // 添加下载链接
    addDownloadLink(type) {
      this.downloadLinks[type].push({
        name: '',
        url: '',
        versionId: this.currentVersion.id,
        type: type
      })
    },
    // 移除下载链接
    removeDownloadLink(type, index) {
      this.downloadLinks[type].splice(index, 1)
    },
    // 保存下载链接
    saveDownloadLinks() {
      const allLinks = [...this.downloadLinks.card, ...this.downloadLinks.line]
      // 验证
      const hasEmptyField = allLinks.some(link => !link.name || !link.url)
      if (hasEmptyField) {
        this.$message.error('链接名称和下载地址不能为空')
        return
      }
      
      // 先删除原有链接，再添加新链接
      downloadApi.deleteByVersionId(this.currentVersion.id).then(() => {
        if (allLinks.length > 0) {
          downloadApi.batchAddDownload(allLinks).then(() => {
            this.$message.success('保存成功')
            this.downloadDialog.visible = false
          })
        } else {
          this.$message.success('保存成功')
          this.downloadDialog.visible = false
        }
      })
    },
    // 获取地区名称
    getRegionName(regionCode) {
      return this.regionMap[regionCode] || regionCode
    },
    // 返回上一页
    goBack() {
      this.$router.push({ name: 'Phone' })
    },
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      if (date.includes('YYYY')) return date.replace('YYYY', new Date().getFullYear())
      
      try {
        const d = new Date(date)
        if (isNaN(d.getTime())) return date
        
        const year = d.getFullYear()
        const month = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      } catch (e) {
        console.error('日期格式化错误:', e)
        return date
      }
    }
  }
}
</script>

<style scoped>
.version-container {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
}
.search-bar {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.download-links {
  padding: 10px;
}
.download-link-item {
  display: flex;
  margin-bottom: 10px;
}
.link-name {
  width: 180px;
  margin-right: 10px;
}
.link-url {
  flex: 1;
  margin-right: 10px;
}
.download-link-actions {
  margin-top: 20px;
  text-align: center;
}
</style> 